using Microsoft.AspNetCore.Mvc;
using WebapiTemplate.Infrastructure.Persistence;
using WebapiTemplate.Domain.Entity;
using WebapiTemplate.Application.Common;

namespace WebapiTemplate.Api.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IRepository<FilesInfo> _filesInfo;
    //上传文件的信息表
    // public EfRepository<FilesInfo> _filesInfo = new EfRepository<FilesInfo>();
    
    

    public WeatherForecastController(ILogger<WeatherForecastController> logger,IRepository<FilesInfo> filesInfo)
    {
        _logger = logger;
        _filesInfo = filesInfo;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    //测试图片文件上传
    [HttpPost]
    [Route("Upload/FormImg")]
    public dynamic Getimages(List<IFormFile> files)
    {
        //消除跨域问题
        HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        if (files.Count < 1)
        {
            return "文件为空";
        }
        //返回保存文件的详细信息
        List<dynamic> saveFilesInfo = new List<dynamic>();


        //手动一个存放图片的文件路径名称
        var now = DateTime.Now;
        // var filePath = string.Format(
        //     "/Uploads/{0}/{1}/{2}/",
        //     now.ToString("yyyy"),
        //     now.ToString("yyyyMM"),
        //     now.ToString("yyyyMMdd")
        // );

        //获取当前web目录
        var webapiRootPath = Directory.GetCurrentDirectory();
        //存放文件的目录
        var fileRootPath = webapiRootPath + "/Uploads";
        //如果目录不存在就创建
        if (!Directory.Exists(fileRootPath))
        {
            Directory.CreateDirectory(fileRootPath);
        }
        //开始写入文件...
        try
        {
            foreach (var item in files)
            {
                if (item != null)
                {
                    #region  文件过滤

                    //过滤文件后缀
                    //var fileExtension = Path.GetExtension(item.FileName);--fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal)
                    string[] permittedExtensions = { ".txt", ".pdf" ,".jpg"};

                    var ext = Path.GetExtension(item.FileName).ToLowerInvariant();

                    if (string.IsNullOrEmpty(ext) || !permittedExtensions.Contains(ext))
                    {
                        break;
                    }
                    //过滤文件大小
                    if (item.Length > 1024 * 1024 * 2) //2M
                    {
                        break;
                    }

                    #endregion
                    //原文件名
                    var OriginalName = item.FileName;
                    //原文件后缀
                    var Suffix = Path.GetExtension(OriginalName);
                    //文件类型
                    var FileType = item.ContentType;
                    //上传日期获取时间戳
                    var SaveDateTime = DateTime.Now.ToString("yyMMddhhmmssfff");
                    //文件字节大小
                    var FileSize = item.Length;

                    //最后的保存文件的完整路径
                    var SaveFileName = Path.Combine(fileRootPath,SaveDateTime)+Suffix;

                    //插入图片数据
                    using (
                        //在指定路径中创建文件
                        FileStream fs = System.IO.File.Create(SaveFileName)
                    )
                    {
                        //从当前item流中读取字节并将它们写入另一个fs文件流。两个流的位置都按复制的字节数前进
                        item.CopyTo(fs);
                        //清除此fs流的缓冲区，使得所有缓冲数据都写入到文件中
                        fs.Flush();
                    }

                        FilesInfo objinfo = new FilesInfo();

                        objinfo.OriginalName = OriginalName;
                        objinfo.Suffix = Suffix;
                        objinfo.FileType = FileType;
                        objinfo.SaveDateTime = SaveDateTime;
                        objinfo.SaveFileName =SaveFileName;
                        objinfo.FileSize = FileSize;

                        //上传进数据库表
                         _filesInfo.Add(objinfo);

                        //上传成功的文件添加进信息集合中
                        saveFilesInfo.Add(objinfo); 
                    }
                    //item == null
                    else{
                        break;
                    }
                }
            
            //上传过程中若没有异常则返回后端处理文件的详细信息
            return new
            {
                code = 1000,
                saveFilesInfo = saveFilesInfo
            };
        }
        //上传过程中产生异常
        catch (Exception ex)
        {
            return new
            {
                code = 400,
                msg = ex.ToString()
            };
        }
    }
}
//https://blog.51cto.com/u_11990719/4025765
//https://blog.csdn.net/qq_41841878/article/details/89996131

/*


6 配置文件
异步形式

7 测试几个参数类型
8 接口-实现类
*/